import utils from './utils';
import hilog from '@ohos.hilog';
import { XLog, LogLevel, OhPrinter, FilePrinter, LogConfiguration, DateFileNameGenerator, FileSizeBackupStrategy, FileLastModifiedCleanStrategy, ConsolePrinter } from '@ohos-port/xlog-ts';

class logger {
  private readonly domain: number = 0xFF00;
  private readonly prefix: string = 'm_manga';
  private readonly format: string = '%{public}s, %{public}s';

  public init(filesDir: string): void {
    try {
      let config = new LogConfiguration.Builder()
        .setTag(this.prefix)
        .setLogLevel(LogLevel.ALl)
        .build();
      let printer = new FilePrinter.Builder(`${filesDir}/logs`)
        .setFileNameGenerator(new DateFileNameGenerator())
        .setBackupStrategy(new FileSizeBackupStrategy(5 * 1024 * 1024))
        .setCleanStrategy(new FileLastModifiedCleanStrategy(7 * 24 * 60 * 60 * 1000))
        .build();
      XLog.init(config, [printer, new OhPrinter(), new ConsolePrinter()]);
    } catch (e) {
      hilog.error(this.domain, this.prefix, this.format, e);
    }
  }

  public info(msg: string, show?: boolean): void {
    try {
      hilog.info(this.domain, this.prefix, this.format, msg);
      XLog.i(msg);
      if (show)
        utils.showPopup('发生错误：' + msg);
    } catch (e) {
      console.log(e);
    }
  }

  public error(e: any, show?: boolean): void {
    try {
      let msg = `error message:${e?.message} / stack:${e?.stack}`;
      hilog.error(this.domain, this.prefix, this.format, msg);
      XLog.e(msg);
      if (show)
        utils.showPopup('发生错误：' + msg);
    } catch (e) {
      console.log(e);
    }
  }
}
export default new logger();